package com.order.frontend.order.controller.ChaController;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.order.frontend.order.Entity.Message.Messages;
import com.order.frontend.order.mapper.MessageMapper;
import com.order.frontend.order.service.PrivateChatRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;

import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

@Controller
public class UserChatController {
    @Autowired
    private MessageMapper messageMapper; // 假设有对应的Mapper
    @Autowired
    PrivateChatRedisService privateChatRedisService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    // 接收客户端消息
    @MessageMapping("/chat/{roomId}")
    public void handleUser(  @DestinationVariable String roomId,
                             @Payload Messages message){
        // 1. 验证消息
        if (isValidMessage(message)) {
            // 2. 广播到当前直播间
            System.out.println("收到消息");
            messagingTemplate.convertAndSendToUser(message.getReceiverId(), "/queue/messages", message);
            // 4. 如果接收者不在线，存储离线消息
            if (!privateChatRedisService.isUserOnline(message.getReceiverId())) {
                messagingTemplate.convertAndSendToUser(message.getSenderId(), "/queue/delivered",
                        "消息已发送，对方不在线");
            } else {
                messagingTemplate.convertAndSendToUser(message.getSenderId(), "/queue/delivered",
                        "消息已送达");
            }
            // 5. 存储消息到Redis
            privateChatRedisService.savePrivateMessage(message);
            // 2. 异步存储到数据库（不阻塞消息处理）
            saveMessageToDatabaseAsync(message);
        }

    }
    // 用户上线时获取离线消息
    @MessageMapping("/chat/connect")
    public void userConnect(@Payload String userId) {
        // 设置用户在线状态
        privateChatRedisService.setUserOnline(userId);

        // 清除未读消息计数
        privateChatRedisService.clearUnreadCount(userId);
    }

    @Async
    public void saveMessageToDatabaseAsync(Messages message) {
        try {
            // 存储到数据库
            messageMapper.insert(message);
        } catch (Exception e) {
            e.printStackTrace();

        }}

    private boolean isValidMessage(Messages message) {
        // 实现消息验证逻辑
        return message != null
                && !StringUtils.isEmpty(message.getContent())
                && message.getContent().length() <= 100;
    }
    private void saveBarrage(Messages  message){

    }
}
